/**
 * Created by zhulizhe on 2017/8/16.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    Dimensions,
    StyleSheet,
    ScrollView,
    Animated,
    RefreshControl,
    DeviceEventEmitter
} from 'react-native';

import Constant from "../Contant";
import {observer} from "mobx-react";
import {observable, action, computed, observe} from 'mobx'
import {GradientButton} from "../component/Button";
const {width, height} = Dimensions.get('window')
import RequestUtil from "../util/NetUtil";
import shoppingCartStore from '../../luojs/store/ShoppingCartStore'


// 价格标签
export const PriceLabel = ({price,color=Constant.REDCOLOR})=>{
    let priceStr = price == 0 ? 0.00 : price/100.0 ;

    let sepStrs = new String(priceStr.toFixed(2)).split('.') ;
    return <View>
        <Text style={{color:color,fontSize:18}}>
            <Text style={{color:color,fontSize:14}}>¥</Text>
            {sepStrs[0]}
            <Text style={{color:color,fontSize:14}}>.{sepStrs[1]}</Text>
        </Text>
    </View>
}


const Header = observer(({shop})=>{
    return <View
        style={[{flexDirection:'row',paddingVertical:15,alignItems:'center'},styles.borderBottom]}>
        <View style={{paddingHorizontal:15}}>
            <Image source={require('../../asserts/home/shoppingcart_icon_station.png')}/>
        </View>
        <Text>{shop.shopName}</Text>
    </View>
})

const Footer = ({totalPrice,confirm})=>{
    return <View style={{flexDirection:'row',justifyContent:'space-between',padding:10,alignItems:'center'}}>
        <View style={{flexDirection:'row',alignItems:'center'}}>
            <Text>合计：</Text>
            <PriceLabel price={totalPrice}/>
        </View>
        <View style={{height:36,width:90,borderRadius:4}}>
            <GradientButton
                round={true}
                title="去结算"
                colors={['#ff680f', '#ff2d2d']}
                onPress={confirm}/>
        </View>
    </View>
}

export const Option = observer(({selectCount=1,minus,plus})=>{
    let Minus = <TouchableOpacity
        onPress={minus&&minus}
        style={[styles.option, styles.center,{borderWidth:1,borderColor:'gray',height:25}]}
        activeOpacity={0.9}>
        <Image source={require('../../luoasserts/shop/btn_subtract.png')}/>
    </TouchableOpacity>

    if (selectCount == 0) {
        return null
    }
    return <View style={{
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    }}>
        {Minus}
        <Text style={{
            paddingHorizontal: 5,
            width: 40,
            fontSize: 16,
            textAlign: 'center',
            backgroundColor:'#00000000',
            borderBottomColor: 'gray',
            borderBottomWidth: 1,
            borderTopWidth:1,
            borderTopColor:'gray',
            height:25
        }}>{selectCount != 0 ? selectCount+'' : ''}</Text>
        <TouchableOpacity
            onPress={plus&&plus}
            style={[styles.option, styles.center,{borderWidth:1,borderColor:'gray',height:25}]}
            activeOpacity={0.9}>
            <Image source={require('../../luoasserts/shop/btn_add.png')}/>
        </TouchableOpacity>
    </View>
})

export const ProductItemCell = observer(({product,minus,plus})=>{
    let sourceIcon;
    product.productType=='水票'?sourceIcon=require('../../luoasserts/tiket/goods_ticket_bg@2x.png'):sourceIcon={uri:product.productImage==null?'':product.productImage[0]};
    return <TouchableOpacity
        activeOpacity={0.9}
        onPress={()=>{

        }}
        style={{flexDirection:'row',paddingVertical:10,alignItems:'center'}}>
        <View style={{flex:9}}>
            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                <View style={{flexDirection:'row'}}>
                    <View style={{padding:5}}>
                        <Image
                            defaultSource={require('../../asserts/common/default_productItem.png')}
                            resizeMode='contain'
                            style={{
                                width: width * 0.8 * 0.3 - 10,
                                height: width * 0.8 * 0.3 - 10,
                            }}
                            source={sourceIcon}/>
                    </View>
                    <View style={{justifyContent:'space-around',paddingLeft:10}}>
                        <Text style={{color:Constant.TEXT_COLOR_2,fontSize:16}}>{product.name}</Text>
                        <Text style={{color:Constant.TEXT_COLOR_6,fontSize:12}}></Text>
                        <PriceLabel price={product.currentPrice}/>
                    </View>
                </View>
                <View style={{justifyContent:'flex-end',paddingRight:15}}>
                    <Option
                        selectCount={product.selectCount}
                        minus={minus}
                        plus={plus}
                    />
                </View>
            </View>
            <View style={styles.separatorLine}/>
        </View>
    </TouchableOpacity>
})

@observer
class Shop extends Component{

    // 加减购物车
    updateProduct(product,type='increase'){
        RequestUtil.requestData('shop/shoppingcart/' + type, {
            "productItemId": product.productItemId,
            "productType": product.type,
            "shopId": this.props.shop.shopId,
        }).then(resp => {
            if(resp!= undefined){
                let {totalPrice, productItemActionModel} = resp;
                let {resultMount} = productItemActionModel;
                product.updateCount(resultMount);
                this.updateTotalPrice(totalPrice);
                if(resultMount==0)DeviceEventEmitter.emit('refreshShopList');//商品个数减到0刷新购物车
                shoppingCartStore.getShoppingCart();//刷新luojs版本购物车数量
            }

        })
    }

    updateTotalPrice(totalPrice){
        this.props.shop.updateTotalPrice(totalPrice)
    }


    render(){
        let {totalPrice, productItemModels,shopId} = this.props.shop;
        return <View style={{backgroundColor:'#fff',marginVertical:5}}>
            <Header
                shop={this.props.shop}/>
            {
                productItemModels.map((p,index)=>{
                    return <ProductItemCell
                        key={index}
                        minus={()=>{
                            this.updateProduct(p,'decrease');
                        }}
                        plus={()=>{
                            this.updateProduct(p);
                        }}
                        product={p}/>
                })
            }
            <Footer
                confirm={()=>{
                    if(totalPrice==0)return;
                    this.props.navigation.navigate('ConfirmOrder', {shopId: shopId});
                }}
                totalPrice={totalPrice}/>
        </View>
    }
}

class ShopModel{
    @observable _totalPrice = 0 ;
    // @observable _selected = true ;

    constructor(shop){
        this.selectCount = shop.selectCount ;
        this._totalPrice = shop.totalPrice ;
        this.shopId = shop.shopId ;
        this.shopName=shop.shopName;
        this.productItemModels = shop.productItemModels.map(p=>{
            return new ProductItemModel(p);
        })
    }

    @action
    updateTotalPrice(price){
        this._totalPrice = price ;
    }

    @computed get totalPrice(){
        return this._totalPrice ;
    }
}

class ProductItemModel {
    @observable _selectCount = 0;

    constructor(item) {
        this.productItemId = item.productItemId;
        this.originalPrice = item.originalPrice;
        this.currentPrice = item.currentPrice;
        this._selectCount = item.selectCount;
        this.saleMount = item.saleMount;
        this.name = item.name;
        this.productImage = item.productImage ;
        this.productType = item.productType ;
    }


    @computed
    get selectCount() {
        return this._selectCount;
    }


    @action
    updateCount(count) {
        this._selectCount = count;
    }

}


@observer
export default class ShoppingCart extends Component{

    @observable shopList = [] ;
    @observable isRefreshing=true;
    static navigationOptions = ({ navigation, screenProps }) =>({
        title: '购物车',
        headerTitleStyle:{alignSelf:'center'},
        headerStyle: {
            backgroundColor:'#fff'
        },
    })

    componentDidMount(){
        this.getShopList();
        this.refreshShopList();
    }

    componentWillUnmount(){
        this.refresh.remove();
    }
    refreshShopList(){
        this.refresh= DeviceEventEmitter.addListener('refreshShopList', () => {
            this.getShopList();
        })
    }
    getShopList(){
        RequestUtil.requestData('shoppingCart/list', {}).then((shopppingCarts) => {
            LOG('shopppingCarts------------'+JSON.stringify(shopppingCarts))
            if (shopppingCarts != undefined) {
                let shops = [] ;
                shopppingCarts.list.forEach(shop=>{
                    if(shop.productItemModels.length!=0)shops.push(new ShopModel(shop))
                })
                this.shopList = shops ;
                this.isRefreshing=false;
            }
        })
    }
    onRefresh(){
        this.getShopList();
    }
    render(){
        return <View style={{flex:1}}>
                {
                    this.shopList.length==0?<View style={{flex:1,alignItems:'center',justifyContent:'center',backgroundColor:'white'}}>
                        <Text>购物车为空</Text>
                    </View>:
                        <ScrollView style={styles.flex}
                                    refreshControl={<RefreshControl
                                        refreshing={this.isRefreshing}
                                        onRefresh={this.onRefresh.bind(this)}
                                        tintColor={Constant.TEXT_COLOR_9}
                                    />}>
                        {
                            this.shopList.map((shop,index)=>{
                                return <Shop
                                    key={index}
                                    navigation={this.props.navigation}
                                    shop={shop}/>
                            })
                        }
                    </ScrollView>
                 }
            </View>
    }
}

const styles = {
    flex:{
        flex:1,
        backgroundColor:Constant.GRAYBGCOLOR
    },
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth,
    },
    separatorLine:{
        backgroundColor:Constant.SEPLINECOLOR,
        height:StyleSheet.hairlineWidth,
        width:'80%',
        marginTop:10,
        alignSelf:'flex-end',
        marginRight:10,
    },

    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    borderTop: {
        borderTopColor: Constant.SEPLINECOLOR,
        borderTopWidth: 1
    },
    option: {
        paddingHorizontal:10
    },
}